<template>
	<view class="uiwu uiwu-ios" :style="{'padding-top': uiwu.statusBar() +'px'}">
		<view class="uiwu-box">
			<!-- 头部信息 -->
			<uiwu-goods-header :dataInfo="dataInfo" @changTips="showTips=true" />
			
			<view class="uiwu-video">
				<view class="uiwu-video-box">
					<view id="myVideo" ref="myVideo"></view>
					<view v-if="showHave && isExecute && duration > 0" class="daojishi">{{duration}}s</view>
				</view>
				<!-- <web-view :fullscreen="false" src="https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/J92077605/1.hd.live&autoplay=1&accessToken=at.6yst2nfxdpu8wm2x96k6qg9l6nzrc3n7-1e876ojpml-1vofved-kv9qzrgyo"></web-view> -->
				<view class="uiwu-video-top uiwu-flex-space">
					<view v-if="!thatUser"></view>
					<view v-else class="left">
						<image v-show="thatUser.is_vip" src="/static/huanguan.png" mode="widthFix"></image>
						<image :src="thatUser.avatar" mode="aspectFill" style="border-radius: 50%"></image>
						<image src="/static/green.png" mode="widthFix"></image>
					</view>
					<view class="right uiwu-flex-space">
						<view class="image" v-if="roomlist.length > 3">
							<image v-for="(item,index) in 3" :key="index" :src="roomlist[index].avatar" mode="aspectFill"></image>
						</view>
						<view class="image" v-else>
							<image v-for="(item,index) in roomlist" :key="index" :src="item.avatar" mode="aspectFill"></image>
						</view>
						<view class="text">
							{{roomlist.length}}人 <br> 在房间
						</view>
					</view>
				</view>
				<!-- 控制音频 -->
				<view class="uiwu-audio">
					<image src="/static/audio.png" v-if="isAudio" mode="widthFix" @tap.stop="swiperAudio"></image>
					<image src="/static/stopaidop.png" v-else mode="widthFix" @tap.stop="swiperAudio"></image>
				</view>
				<!-- 广播抓中的人 -->
				<view class="uiwu-guangbo uiwu-flex-align" v-if="resultAllData">
					<image :src="resultAllData.avatar" mode="aspectFill"></image>
					<text class="uiwu-hidden1">{{resultAllData.nickname}}抓中了{{resultAllData.product_name}}</text>
				</view>
				<view class="swiper-root uiwu-flex-column uiwu-flex-center" @tap.stop="swiperDevice">
					<image src="/static/qiehuanroot.png" mode="widthFix"></image>
					<text>切换房间</text>
				</view>
				<view class="button" @click="ezuikit.perspectives()">切换视角</view>
			</view>
			<!-- 开始按钮 -->
			<uiwu-goods-start ref="isReservation"  :dataInfo="dataInfo" @moneyBuZu="showMoney=true" @onStart="onStartFun" @changeUpdate="getDeviceinfo" v-if="!showHave" />
			<!-- 游戏进行中 -->
			<uiwu-goods-have :isExecute="isExecute" :item="dataInfo" v-else @onStart="gardStart" ></uiwu-goods-have>
		</view>
		<view class="uiwu-goods-yeool">
			<view class="uiwu-goods-detail">
				<view class="title">零食详情</view>
				<view style="padding: 20rpx;">
					<mp-html :content="description"></mp-html>
				</view>
			</view>
		</view>
		
		<uiwu-goods-tips v-model="showTips"></uiwu-goods-tips>
		<uiwu-goods-NoPopup :dataInfo="dataInfo" v-if="noGoodsPopup" @continue="continueGame" @closegrme="closegrme" />
		<uiwu-goods-yePopup :dataInfo="dataInfo" :goodsName="goodsName" v-if="yesGoodsPopup" @continue="continueGame" @closegrme="closegrme" />
		<uiwu-start-popup :dataInfo="dataInfo" @onStart="onStartCange" v-if="isYuyueStart" @closegrme="closegrme" />
		<uiwu-popup-model v-if="showMoney" v-model="showMoney" @confirm="confirm">
			<text>哎呀，金币不够了</text>
		</uiwu-popup-model>
		<view id="getdevId" style="display: none;">{{devId}}</view>
		<view id="getToken" style="display: none;">{{getToken}}</view>
	</view>
</template>

<script setup lang="ts">
	
	import { onLoad , onUnload } from '@dcloudio/uni-app';
	import { inject, ref , toRef } from "vue";
	import { deviceinfo , startGren , cancel_subscribe, deviceRandInfo, sysConfig } from "@/api/api";
	import { uiwu } from '@/config/config';
	const socket = inject<any>('socket')
	const showTips = ref<boolean>(false)//显示说明
	const showHave = ref<boolean>(false)
	const dataInfo = ref<object>({});
	const devId = ref(null)
	const noGoodsPopup = ref(false)
	const yesGoodsPopup = ref(false)
	const goodsName = ref(null)
	const isYuyueStart = ref(false)
	const isReservation = ref(null)
	const roomlist = ref([])
	const store = inject<any>('store');
	const userInfo = toRef(store.state,'userInfo')
	const isExecute = ref<boolean>(true) //下抓锁定条件
	const roomId = ref(null)
	const getToken = uni.getStorageSync('token');
	const thatUser = ref(null)
	const showMoney = ref(false)
	const AudioContext = uni.createInnerAudioContext()
	const duration = ref(0)
	let t_duration = null;
	const description = ref(null)
	const isAudio = ref(true)
	const resultAllData = ref(null)
	let setTimeOutRestle = null
	const getDeviceinfo = async (id:string = devId.value) : Promise<any> => {
		const { data } = await deviceinfo(id);
		data.product_info.description = uiwu.richtext(data.product_info.description)
		description.value = data.product_info.description
		dataInfo.value = data
		const { device_info } = data;
		duration.value = device_info.duration
		// #ifdef APP-PLUS
		socket.send(JSON.stringify({
			type:'joinGroup',
			device_id:device_info.id
		}));
		// #endif
	}
	const confirm = () => {
		uni.switchTab({
			url:'/pages/recharge/recharge'
		})
	}
	const swiperAudio = () : void => {
		isAudio.value = !isAudio.value
		if(!isAudio.value) AudioContext.pause()
		if(isAudio.value) AudioContext.play()
	}
	/**
	 * getSysConfig 获取音频地址
	 */
	const getSysConfig = async () => {
		const {data:{data}} = await sysConfig();
		isAudio.value = userInfo.value.is_open_music ? true : false
		if(userInfo.value.is_open_music && data){
			AudioContext.src = data
			AudioContext.loop = true
			AudioContext.play()
			AudioContext.onCanplay(()=>{
				console.log('可以播放了');
			})
			AudioContext.onPlay(()=>{
				console.log('播放了');
			})
			AudioContext.onError(()=>{
				console.log('播放错误');
			})
		}
	}
	const gardStart = () => {
		isExecute.value = false
		clearInterval(t_duration)
	}
	/**
	 * 开始游戏的回调 回调房间id 用于继续游戏
	 */
	const onStartFun = (id) => {
		roomId.value = id
	}
	uni.$on('receivedMsgCallBack',(res)=>{
		try{
			const {data,type,user_info,status} = JSON.parse(res);
			// 获取抓取结果
			if(type == 'grabResult'){
				if(data.status == 0) noGoodsPopup.value = true
				if(data.status == 1){
					goodsName.value = data.product_name
					yesGoodsPopup.value = true
				}
				showHave.value = false
			}
			if(type == 'subscribeStart') isYuyueStart.value = true // 预约到自己上场弹窗
			if(type == 'groupUserList') roomlist.value = data //当前房间人数
			if(type == 'currentPlayer') thatUser.value = user_info //当前玩家信息
			if(type == 'deviceStatus') dataInfo.value.device_info.state = status //设备状态
			if(type == 'subscribeNum') dataInfo.value.subscribe_num = data.subscribe_num //预约人数
			 // 广播推送 抓中奖品的人
			if(type == 'grabResultAll') {
				resultAllData.value = data
				clearTimeout(setTimeOutRestle) //先清除定时器
				// 5秒后关闭广播弹窗
				setTimeOutRestle = setTimeout(()=>{
					resultAllData.value = null
				},5000)
			}
			//投币结果
			if(type == 'insertCoinResult'){
				if(status != 1) return uiwu.toast('投币失败，请重试')
				showHave.value = true
				clearInterval(t_duration)
				t_duration = setInterval(()=>{
					duration.value--
					if(duration.value == 0){
						clearInterval(t_duration)
					}
				},1000)
			}
		}catch(e){
			console.log(e);
		}
	})
	const onStartCange = () => {
		showHave.value = true;
		isYuyueStart.value = false
	}
	/**
	 * 没有抓中奖品后，弹窗继续游戏
	 */
	const continueGame = async () : Promise<any> => {
		const { device_info } = dataInfo.value;
		const result = await startGren({
			device_id:device_info.id,
			room_id:roomId.value
		})
		noGoodsPopup.value = false
		isExecute.value = true
		if(!result) return 
		if(result.data.room_id == 'now_money_lack' || result.data.id == 'now_money_lack'){
			closegrme()
			showMoney.value = true
			return
		}
		duration.value = dataInfo.value.device_info.duration
		clearInterval(t_duration)
		t_duration = setInterval(()=>{
			duration.value--
			if(duration.value == 0){
				clearInterval(t_duration)
			}
		},1000)
		if(result.data.id) roomId.value = result.data.id
	}
	/**
	 * closegrme 没有抓中奖品后 默认倒计时结束，游戏结束
	 */
	const closegrme = () =>{
		roomId.value = null
		isExecute.value = true
		showHave.value = false
		noGoodsPopup.value = false
		thatUser.value = null
		duration.value = dataInfo.value.device_info.duration
		yesGoodsPopup.value = false
		if(isYuyueStart.value){
			isYuyueStart.value = false
			isReservation.value.setisReservation()
			getDeviceinfo()
		}
		getDeviceinfo()
	}
	/**
	 * swiperDevice 切换房间 
	 * 这里利用的是页面关闭重新打开的操作模式实现数据重载。
	 * 因为牵扯到了renderjs 不知道怎么重新触发故而只能使用次下策方式
	 */
	const swiperDevice = async () : Promise<any> => {
		const { device_info } = dataInfo.value;
		const { data:{id} } = await deviceRandInfo(device_info.id);
		uni.redirectTo({
			url:`/pages/index/detail?id=${id}`
		})
	}
	onUnload(()=>{
		AudioContext.destroy()
		uni.$off('receivedMsgCallBack')
		if(isReservation.value.getisReservation()){
			cancel_subscribe({device_id:dataInfo.value.device_info.id})
		}
		// #ifdef APP-PLUS
		socket.send(JSON.stringify({
			type:'leaveGroup',
			device_id:dataInfo.value.device_info.id
		}));
		// #endif
	})
	onLoad(({id})=>{
		devId.value = id
		getDeviceinfo();
		getSysConfig()
	})
</script>
<script module="ezuikit" lang="renderjs">
	let player = null;
	let monitor = null;
	let VideoUrl = null;
	let IndexNum = 0;
	const urls = 'http://zww1379.440.red/api/';
	export default {
		async mounted() {
			const {data:{monitor_list}} = await this.deviceinfo(document.getElementById('getdevId').innerHTML);
			monitor = monitor_list || []
			if(!monitor.length) return console.log('没有监控地址可以使用');
			VideoUrl = monitor[0].monitor_url
			if (typeof window.EZUIKit !== 'undefined') {
				this.initPlayer();
			} else {
				const script = document.createElement('script');
				script.src = 'static/ezuikit.js';
				script.onload = this.initPlayer.bind(this)
				document.head.appendChild(script)
			}
		},
		methods:{
			deviceinfo(id){
				const token = document.getElementById('getToken').innerHTML;
				return new Promise((resolve,reject)=>{
					fetch(`${urls}device/info/${id}`,{
						headers: {
						    "Authori-zation": `Bearer ${token}`
						}
					})
					.then(response => response.json())
					.then((res)=>{
						resolve(res)
					})
				})
			},
			get_access_token(){
				return new Promise((resolve,reject)=>{
					fetch(`${urls}monitor/get_access_token`,{
						headers: {
						    "Authori-zation": `Bearer ${document.getElementById('getToken').innerHTML}`
						}
					})
					.then(response => response.json())
					.then((res)=>{
						resolve(res)
					})
				})
			},
			/**
			 * 切换视角
			 */
			perspectives(){
				IndexNum < monitor.length - 1 ? IndexNum++ : IndexNum = 0
				VideoUrl = monitor[IndexNum].monitor_url
				this.initPlayer()
			},
			async initPlayer() {
				const { offsetHeight , offsetWidth } = document.getElementById('myVideo');
				const {data:{data:{accessToken}}} = await this.get_access_token();
				player = new EZUIKit.EZUIKitPlayer({
					id: 'myVideo',
					accessToken: accessToken,
					url: VideoUrl,
					plugin: ['talk'],
					width: offsetWidth,
					height: offsetHeight
				});
				window.player = player;
			},
		}
	}
</script>
<style lang="scss">
	page{
		background: url('../../static/goodszige.png') no-repeat 0 0 #EF821E;
		background-size: cover;
	}
	.uiwu{
		padding-left: 15rpx;
		padding-right: 15rpx;
	}
	.uiwu-box{
		width: 100%;
		height: 1395rpx;
		background: url('../../static/detaigb.png') no-repeat 0 0;
		background-size: 100% auto;
		position: relative;
		z-index: 9;
	}
	
	.uiwu-video{
		width: 100%;
		height: 971rpx;
		background: url('../../static/videoborder.png') no-repeat 0 84rpx;
		background-size: 100% 800rpx;
		position: relative;
		.uiwu-audio{
			position: absolute;
			right: 40rpx;
			top: 104rpx;
			image{
				width: 56rpx;
			}
		}
		.uiwu-guangbo{
			position: absolute;
			left: 40rpx;
			top: 200rpx;
			max-width: 360rpx;
			height: 60rpx;
			background: rgba(0,0,0,0.4);
			border-radius: 30rpx;
			border: 1rpx solid #000000;
			padding: 2rpx;
			padding-right: 15rpx;
			image{
				width: 54rpx;
				height: 54rpx;
				border-radius: 50%;
				margin-right: 15rpx;
			}
			text{
				font-size: 24rpx;
				font-weight: 500;
				color: #FFFFFF;
			}
		}
		.uiwu-video-box{
			width: 100%;
			height: 100%;
			padding: 4px 20rpx;
			overflow: hidden;
			position: relative;
			#myVideo{
				width: 100%;
				height: 100%;
				background-color: #fff;
				overflow: hidden;
			}
			.daojishi{
				position: absolute;
				left: 40rpx;
				bottom: 40rpx;
				font-size: 60rpx;
				color: #FFF;
			}
		}
		.left{
			position: relative;
			image{
				&:nth-child(1){
					width: 36rpx;
					position: absolute;
					left: 6rpx;
					top: 6rpx;
				}
				&:nth-child(2){
					width: 80rpx;
					height: 80rpx;
				}
				&:nth-child(3){
					position: absolute;
					right: 6rpx;
					bottom: 6rpx;
					width: 20rpx;
				}
			}
		}
		.swiper-root{
			position: absolute;
			right: 0;
			bottom: 255rpx;
			width: 100rpx;
			height: 104rpx;
			background: linear-gradient(180deg, #FCE5C7 0%, #FAC500 100%);
			border-radius: 20rpx;
			border: 3rpx solid #231815;
			image{
				width: 56rpx;
			}
			text{
				font-size: 20rpx;
				font-weight: bold;
				color: #913500;
			}
		}
		&-top{
			width: 100%;
			height: 84rpx;
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			padding: 0 37rpx;
			.right{
				width: 214rpx;
				height: 60rpx;
				background: rgba(0,0,0,0.4);
				border-radius: 30rpx;
				border: 3rpx solid #000000;
				box-sizing: content-box;
				.image{
					height: 56rpx;
					image{
						width: 56rpx;
						height: 56rpx;
						border-radius: 50%;
						&:nth-child(2){
							margin-left: -32rpx;
						}
						&:nth-child(3){
							margin-left: -32rpx;
						}
					}
				}
				.text{
					text-align: center;
					font-size: 22rpx;
					font-weight: 500;
					color: #FFFFFF;
					padding-right: 16rpx;
					line-height: 1.2;
				}
			}
		}
		.button{
			width: 600rpx;
			height: 60rpx;
			line-height: 60rpx;
			background: url('../../static/qiehuanshijiao.png') no-repeat 0 3rpx ;
			background-size: 100% 100%;
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			margin: 0 auto;
			text-align: center;
			font-size: 28rpx;
			font-weight: 800;
			color: #231815;
		}
	}
	.uiwu-goods-yeool{
		padding: 17rpx;
		border:3rpx solid #231815;
		background-color: #FAC500;
		margin-top: -32px;
		border-top: 0;
		padding-top: 76rpx;
		border-radius: 32rpx;
	}
	.uiwu-goods-detail{
		background: url('../../static/goodsdetail.png') no-repeat center -4rpx #FFF;
		background-size: 600rpx 60rpx;
		min-height: 400rpx;
		border:3rpx solid #231815;
		border-radius: 32rpx;
		.title{
			text-align: center;
			font-size: 28rpx;
			font-weight: 800;
			color: #FFFFFF;
			line-height: 54rpx;
		}
	}
</style>
